package org.givwenzen.steps;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.core.search.SearchParticipant;
import org.eclipse.jdt.core.search.SearchPattern;
import org.eclipse.jdt.internal.core.ResolvedSourceMethod;
import org.givwenzen.search.GWZSearchRequestor;

public class StepLocator {

    public ResolvedSourceMethod findMethod(String step, IProject project) {
            //TODO: this search can be tuned to search only once and return all the implementations. Then match from memory.
            IJavaProject myJavaProject = (IJavaProject) JavaCore.create(project);
            SearchPattern pattern = SearchPattern
                .createPattern("org.givwenzen.annotations.DomainStep", IJavaSearchConstants.ANNOTATION_TYPE, IJavaSearchConstants.REFERENCES, SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE);
            IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] {myJavaProject});
            final GWZSearchRequestor requestor = new GWZSearchRequestor(step);                                

            //search
            SearchEngine searchEngine = new SearchEngine();
            try {
                searchEngine.search(pattern, new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()}, scope, requestor, null);
            } catch (CoreException e) {
                throw new RuntimeException("Something went wrong when searching for Step", e);
            }
            
            return requestor.methodToJump;
    }
}